package com.shujia.flink.state;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.HashMap;

public class Demo01NoState {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStream<String> wordDS = env.socketTextStream("master", 8888);

        // 统计每个单词的数量
        wordDS.keyBy(word -> word)
                .process(new KeyedProcessFunction<String, String, Tuple2<String, Integer>>() {
                    // 同Task中的每条数据会执行一次
                    // 同一个Task中的不同的Key会共用变量
//                    Integer cnt = 0;

                    /*
                    HashMap中的数据是保存在内存中的，所以一旦程序异常停止了，那么重启时无法进行恢复，之前的状态丢失了
                    所以就需要定期将数据保存到可靠的存储系统中，以便错误后的恢复
                     */
                    HashMap<String, Integer> wordCntMap = new HashMap<>();

                    @Override
                    public void processElement(String word, KeyedProcessFunction<String, String, Tuple2<String, Integer>>.Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                        Integer cnt = wordCntMap.getOrDefault(word, 0);
                        cnt++;
                        wordCntMap.put(word, cnt);

                        out.collect(Tuple2.of(word, cnt));
                    }
                }).print();
        env.execute();
    }
}
